package com.rainbow.bam.action;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.rainbow.bam.util.Constant;

import java.util.Collection;

/**
 * 会话管理控制类
 * 
 * @author zhaolei
 * @version $Id: SessionController.java, v 0.1 2015年11月18日 下午3:05:46 zhaolei Exp $
 */
@Controller
@RequestMapping("/sessions")
public class SessionController {

    /**
     * sessionDao
     */
    @Autowired
    private SessionDAO sessionDAO;

    /**
     * 会话列表
     * 
     * @param model
     * @return
     */
    @RequiresPermissions("session:query")
    @RequestMapping(value = "/sessionslist")
    public String list(Model model) {
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        model.addAttribute("sessions", sessions);
        model.addAttribute("sessionCount", sessions.size());
        return "sessions/sessions_list";
    }

    /**
     * 强制退出会话
     * 
     * @param sessionId  会话ID
     * @return
     */
    @RequiresPermissions("session:forceLogout")
    @RequestMapping("/{sessionId}/forceLogout")
    public String forceLogout(@PathVariable("sessionId") String sessionId) {
        try {
            Session session = sessionDAO.readSession(sessionId);
            if (session != null) {
                session.setAttribute(Constant.sessionConstant.SESSION_FORCE_LOGOUT_KEY,
                    Boolean.TRUE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return "redirect:/sessions/sessionslist";
    }

}
